package jp.ac.nitech.matlab.najm.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

import jp.ac.nitech.matlab.najm.io.LiveTrace;
import jp.ac.nitech.matlab.najm.io.TraceFactory;

public class MetaDataMap {
	Map<String, String> file2SNode;
	String mapfile ;
	LiveTrace trace = (LiveTrace)TraceFactory.getTrace();

	private static MetaDataMap instance = new MetaDataMap();
	
	public static MetaDataMap getInstance(){ return instance; }
	
	private MetaDataMap(){
		file2SNode = new Hashtable<String, String>();
		mapfile = SSetting.getInstance().getSetting("mapfile");
		trace.info(this, 0, " mapfile is "+mapfile);
		dummy();
		//load maps		
		this.load(mapfile);
	}
	
	//creates some map dummily
	private void dummy(){
		try{
			file2SNode.put("testget01", "127.0.0.1");
			this.save(mapfile);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	private void printme(){
		trace.info(this, 0, " printing mdm");
		Collection<String> l = file2SNode.values();
		for(Iterator<String> it=l.iterator(); it.hasNext();)
			System.out.println(it.next());
	}
	public String findFile(String target){
		trace.info(this, 0, " searching "+target);
		trace.info(this, 0, " found @ "+file2SNode.get(target));
		return file2SNode.get(target);
	}
	
	public void addFile(String name, String holder){
		file2SNode.put(name, holder);
	}
	public void removeFile(String name){
		file2SNode.remove(name);
	}
	public void close(){
		this.save(mapfile);
	}
	
	private void save(String file){
		try{
			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File(file)));
			out.writeObject(file2SNode);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private void load(String file){
		try{
			ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
			file2SNode = (Hashtable<String, String>)in.readObject();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
